﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;
using Models;
using DbControl;
using System.Configuration;
using System.Xml.Linq;

namespace CentralMonitoring
{
    /// <summary>
    /// 设备信息管理窗体
    /// </summary>
    public partial class DeviceAlarmConfigFrm : Form
    {
        public DeviceAlarmConfigFrm()
        {
            InitializeComponent();
        }
        private int m_currentNodeTag=-1;
        private bool m_isParent = false;
        #region treeview
        private void InitTree()
        {
            this.treeView1.Nodes.Clear();
            DataTable dt = OprDevice.GetdevicesTree(); 
            if (dt != null && dt.Rows.Count > 0)
            {
                DataView dv = dt.DefaultView;
                dv.Sort = "parentid ASC";
                DataRowView[] arrDRV = dv.FindRows("0");
                if (arrDRV.Length == 0)
                    return;
                TreeNode tnNew = null;
                treeView1.BeginUpdate();
                foreach (DataRowView drv in arrDRV)
                {
                    tnNew = this.treeView1.Nodes.Add(drv["device_name"].ToString());
                    tnNew.Tag = drv.Row["id"];
                    CreateTreeNode(ref tnNew, dv);
                }
                treeView1.EndUpdate();
                treeView1.ExpandAll();
            }
        }
        private void CreateTreeNode(ref TreeNode tnParent, DataView dv)
        {
            DataRowView[] arrDrv = dv.FindRows(tnParent.Tag);
            if (arrDrv.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDrv)
            {
                tnNew = tnParent.Nodes.Add(drv.Row["device_name"].ToString());
                tnNew.Tag = drv.Row["ID"].ToString();
                CreateTreeNode(ref tnNew, dv);

            }
        }
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode currentNode = treeView1.GetNodeAt(clickPoint);
                if (currentNode != null)
                {                   
                    treeView1.SelectedNode = currentNode;
                }
                else
                {                   
                    treeView1.SelectedNode = null;
                }
            }

        }
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int nodeId;
            if (e.Node.Nodes.Count > 0)
            {
                e.Node.Expand();                
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid(nodeId,true);
                m_isParent = true;
            }
            else
            {
                nodeId=int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid(nodeId);
                m_isParent = false;
            }
            m_currentNodeTag = nodeId;
        }   
        
        #endregion
        private void SensorsConfigFrm_Load(object sender, EventArgs e)
        {
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            InitTree();
            RefreshGrid("");
            this.WindowState = FormWindowState.Maximized;
        }       
        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)//dataGridView1.Rows.Count
            {
                int nID = (int)dataGridView1.SelectedRows[0].Cells["id"].Value;//(int)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["Id"].Value;
                DeviceEdit dlg = new DeviceEdit();
                dlg.m_type =OprType.Modify;
                dlg.m_Id = nID;
                dlg.m_beforName = dataGridView1.SelectedRows[0].Cells["device_name"].Value.ToString();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    RefreshGrid("");                    
                    //int nodeID = int.Parse(treeView1.SelectedNode.Tag.ToString());
                    //string nodeName = treeView1.SelectedNode.Text;
                    //RefreshGrid(nodeID);
                    InitTree();
                    //treeSetView.SetSelectTreeView(treeView1, nodeName);
                } 
            }
        }        
        #region dataGridView1
        private void RefreshGrid(int parentid,bool isParent=false)
        {
            DataTable dataTable = new DataTable();
            dataTable = OprDeviceAlarmConfig.GetdevicesByTreeNode(parentid,isParent);
            RefreshGrid(dataTable);
        }
        private void RefreshGrid(string name)
        {          
            DataTable dt = OprDeviceAlarmConfig.GetdevicesAlarmConfigByName(name);
            if (dt != null)
            {
                RefreshGrid(dt);
            }
        }
        private void RefreshGrid(DataTable dt)
        {          
            if (dt != null)
            {
                this.dataGridView1.DataSource = dt;
                dataGridView1.Columns["id"].Visible = false;
                dataGridView1.Columns["parentid"].Visible = false;
                dataGridView1.Columns["sensor_id"].Visible = false;         
                dataGridView1.Columns["parameter_id"].Visible = false;
                dataGridView1.Columns["warn_ids"].Visible = false;                      
                dataGridView1.Columns["device_name"].HeaderText = "设备名称";
                dataGridView1.Columns["device_code"].HeaderText = "识别码";                
                dataGridView1.Columns["oil_code"].HeaderText = "油品编码";           
                dataGridView1.Columns["oil_name"].HeaderText = "油品名称";                
                dataGridView1.Columns["flag"].HeaderText = "状态";
                dataGridView1.Columns["device_position"].Visible = false;
                dgSetView.SetFormatDataGridView(dataGridView1);

                for(int i = 0;i < dataGridView1.SelectedRows.Count;i++)
                {
                    int index = dataGridView1.SelectedRows[0].Index; 
                    object warnids = dataGridView1.Rows[index].Cells["warn_ids"].Value;
                    if(warnids != null)
                    {  
                        AutoLoadWarnByids(warnids.ToString());
                    }
                     
                }

                
            }
        }
        private void AutoLoadWarnByids(string ids)
        {
            DataTable dt = OprDeviceAlarmConfig.GetRules(ids);
            if (dt != null)
            {
                dataGridView2.DataSource = dt;
                dataGridView2.Columns["Id"].Visible = false;
                dataGridView2.Columns["sensor_id"].Visible = false;
                dataGridView2.Columns["parameter_id"].Visible = false;
                dataGridView2.Columns["rule_code"].HeaderText = "规则名称";
                dataGridView2.Columns["parameter_name"].HeaderText = "指标名称";
                dataGridView2.Columns["upper_upper_value"].HeaderText = "上上限";
                dataGridView2.Columns["upper_value"].HeaderText = "上限";
                dataGridView2.Columns["lower_value"].HeaderText = "下限";
                dataGridView2.Columns["lower_lower_value"].HeaderText = "下下限";
                dataGridView2.Columns["Flag"].Visible = false;
                dgSetView.SetFormatDataGridView(dataGridView2);
            }


        }
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e == null || e.Value == null || !(sender is DataGridView))
            {
                return;
            }
            DataGridView dgv = (DataGridView)sender;
            object originalValue = e.Value;
            int dValue = 0;
            if (dgv.Columns[e.ColumnIndex].DataPropertyName == "flag")
            {
                if (e.Value != null && int.TryParse(e.Value.ToString(), out dValue))
                    e.Value = dValue > 0 ? "启用" : "禁用";
            }
        }
        #endregion
        private void buttonParaSet_Click(object sender, EventArgs e)
        {
            DeviceByOilParaSet dlg = new DeviceByOilParaSet();
            dlg.ShowDialog();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonFind_Click(object sender, EventArgs e)
        {            
            if(!string.IsNullOrEmpty(textBoxDevice.Text))
                RefreshGrid(textBoxDevice.Text);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            ServerEdit dlg=new ServerEdit();
            dlg.ShowDialog();
        }

        private void buttonSensorSet_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)//dataGridView1.Rows.Count
            {
                int nID = (int)dataGridView1.SelectedRows[0].Cells["id"].Value;//(int)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["Id"].Value;
                SensorConfigEdit dlg = new SensorConfigEdit();            
                dlg.m_Id = nID;               
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (m_currentNodeTag > 0)
                        RefreshGrid(m_currentNodeTag,m_isParent);
                    else
                        RefreshGrid("");                   
                }
            }
        }

        private void buttonOilSet_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)//dataGridView1.Rows.Count
            {
                int nID = (int)dataGridView1.SelectedRows[0].Cells["id"].Value;//(int)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["Id"].Value;
                OilConfigEdit dlg = new OilConfigEdit();
                dlg.m_Id = nID;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (m_currentNodeTag > 0)
                        RefreshGrid(m_currentNodeTag, m_isParent);
                    else
                        RefreshGrid("");
                }
            }
        }

        private void buttonWarnSet_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int nID = (int)dataGridView1.SelectedRows[0].Cells["id"].Value;
                RuleConfigEdit dlg = new RuleConfigEdit();
                dlg.m_Id = nID;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (m_currentNodeTag > 0)
                        RefreshGrid(m_currentNodeTag, m_isParent);
                    else
                        RefreshGrid("");
                }
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //string str = dataGridView1.CurrentRow.Cells["device_name"].Value.ToString();
            //MessageBox.Show(str);

           // MessageBox.Show(this.dataGridView1["device_name", e.RowIndex].Value.ToString());
        }
    }
}
